﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Camalot.Common.IO;

namespace Camalot.Common.Extensions {
	public static partial class CamalotCommonExtensions {
		public static byte[] GetBytes ( this FileInfo file ) {
			if ( file == null ) {
				return new byte[0];
			}
			using ( var ms = new MemoryStream ( ) ) {
				using ( var fs = new FileStream ( file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
					var bread = 0;
					var buffer = new byte[4096];
					while ( ( bread = fs.Read ( buffer, 0, buffer.Length ) ) > 0 ) {
						ms.Write ( buffer, 0, bread );
					}
				}
				ms.Position = 0;
				return ms.ToArray ( );
			}
		}

		public static void WriteBytes ( this FileInfo file, byte[] bytes ) {
			if ( file == null || !file.Exists ) {
				throw new FileNotFoundException ( );
			}

			using ( var fs = new FileStream ( file.FullName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read ) ) {
				fs.Write ( bytes, 0, bytes.Length );
			}

		}

		public static String ContentType ( this FileInfo file ) {
			return MimetypesFileTypeMap.DefaultFileTypeMap.GetContentType ( file );
		}

		public static String Extension ( this FileInfo file ) {
			var ext = Path.GetExtension ( file.Name );
			ext = ext.REReplace ( @"^\.", String.Empty );
			return ext;
		}

	}
}
